﻿@inject ITagSearchService tagSearchService
@inject NavigationService navContext
@inject NavigationManager NavigationManager
@inject ContextMenuService contextMenuService

<div>
    <MudAutocomplete T="string" Placeholder="Add a Keyword" SearchFunc="SearchTags"
                     @bind-Value="@TypeAheadTag" @bind-Value:after="CreateNewTags"
                     ShowProgressIndicator="true" MinCharacters="2"
                     CoerceValue="true" DebounceInterval="250" Clearable="true" Immediate="false"
                     Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.Sell"
                     Dense="true" Margin="Margin.Dense" Variant="UIConstants.MudVariant"
                     Disabled="@IsDisabled"
                     class="tag-autocomplete" PopoverClass="tag-autocomplete-popover"/>
</div>


@code {
    private string TypeAheadTag { get; set; }

    [Parameter] public bool IsDisabled { get; set; } = false;

    [Parameter] public required Action<string> OnAddNewtag { private get; set; }

    protected override void OnParametersSet()
    {
        if ( OnAddNewtag == null )
            throw new ArgumentException("No callback specified for OnAddNewTag!");

        base.OnParametersSet();
    }

    private void CreateNewTags()
    {
        if ( !string.IsNullOrEmpty(TypeAheadTag) )
        {
            var newTag = TypeAheadTag;
            Logging.Log($"Saving new tag: {newTag}");

            // Reset the tag
            TypeAheadTag = string.Empty;
            StateHasChanged();

            // Call the callback
            OnAddNewtag(newTag);
        }
    }

    private async Task<IEnumerable<string>> SearchTags(string text, CancellationToken token)
    {
        var results = await tagSearchService.SearchTags(text, token);
        return results.Select(x => x.Keyword);
    }

}